#include "single_file_loger.hpp"

namespace lxz
{

    single_file_loger::single_file_loger()
    {
    }

    single_file_loger::~single_file_loger()
    {
    }

    int32_t single_file_loger::init(log_level level, const char *file)
    {
        level_ = level_;

        fp_ = fopen(file, "w");
        if (!fp_)
        {
            return -1;
        }

        looping_ = true;
        thread_ = std::make_shared<std::thread>(&single_file_loger::flush, this);

        return 0;
    }

    void single_file_loger::flush(void)
    {
        while (looping_)
        {
            {
                std::unique_lock<std::mutex> lock(mutex_);

                cond_var_.wait(lock, [this](void) -> bool
                               { return this->enable_flush_ == true; });

                enable_flush_ = false;

                if (out_queue_.empty() && !(in_queue_.empty()))
                {
                    out_queue_.swap(in_queue_);
                }
            }

            while (!(out_queue_.empty()))
            {
                (void)fputs(out_queue_.front().c_str(), fp_);
                fflush(fp_);

                out_queue_.pop();
            }

            
        }
    }
}